package com.ck.xs.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 孙泽权
 * @version V1.0
 * @Title:
 * @Package
 * @Description: (用一句话描述该文件做什么)
 * @date
 */
@RestController
@RequestMapping("/video")
public class VideoController {

    @GetMapping("/get/video/address")
    public List<Map<String, String>> getVideoAddress() {
        File file = new File("D:\\video");
        List<Map<String, String>> fileNs = new ArrayList<Map<String, String>>();
        String filename = "";
        File[] subFile = file.listFiles();
        for (File value : subFile) {
            // 判断是否为文件夹
            if (!value.isDirectory()) {
                Map<String, String> jsonVideos = new HashMap<>();
                String subFileName = value.getName();
                // 判断是否为mp4结尾
                if (subFileName.trim().toLowerCase().endsWith(".mp4")) {
                    filename = "http://localhost:8080/video/alone/video/play" + subFileName;
                    jsonVideos.put("filename", subFileName);
                    jsonVideos.put("address", filename);
                    fileNs.add(jsonVideos);
                }
            }
        }
        return fileNs;
    }

    /**
     * /video/alone/video/play/
     * @param request
     * @param videoUrl
     * @param response
     */
    @GetMapping(value = "/alone/video/play/{videoUrl}", produces = "application/json;charset=utf-8")
    public void aloneVideoPlay(HttpServletRequest request, @PathVariable("videoUrl") String videoUrl, HttpServletResponse response) {
        InputStream is = null;
        OutputStream os = null;
        try {
            response.setContentType("video/mp4");
            videoUrl = IndexController._basePath+File.separator+videoUrl;
            File file = new File(videoUrl);
            response.addHeader("Content-Length", "" + file.length());
            is = new FileInputStream(file);
            os = response.getOutputStream();
            IOUtils.copy(is, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
